package com.rs.admin.sys.base.controller;

import com.rs.admin.sys.org.entity.User;
import com.rs.admin.sys.org.service.UserService;
import com.rs.admin.sys.org.service.UserTokenService;
import com.rs.common.utils.BCrypt.BCryptUtil;
import com.rs.common.utils.constant.Constant;
import com.rs.common.utils.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录controller
 * @author hedonglin
 * @company 睿思科技
 * @email 1048791780@qq.com
 * @date 2017年12月20
 */
@RestController
@Api(value = "登录接口")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserTokenService userTokenService;


    @PostMapping(value = "/sys/login")
    @ApiOperation(value = "登录",notes = "登录说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType="string", name = "username", value = "用户名", required = true),
            @ApiImplicitParam(paramType = "query", dataType="string", name = "password", value = "密码", required = true)
    })
    public R login(String username, String password){
        if (StringUtils.isBlank(username)){
            return R.error("用户名不能为空");
        }
        if (StringUtils.isBlank(password)){
            return R.error("密码不能为空");
        }

        //1、根据用户名查询用户信息
        User user = userService.findUserByUniqKey(username);
        //2、判断用户是否存在
        if (user == null){
            return R.error("账号不存在");
        }

        //3、判断密码
        if (StringUtils.isNotBlank(user.getPassword())){
            boolean b = BCryptUtil.checkPwd(password,user.getPassword());
            if (!b){
                return R.error("密码不正确");
            }
        }
        //4、判断状态
        if (user.getStatus() == Constant.BaseStatus.FROZEN.getValue()){
            return R.error("账号已被冻结,请联系管理员");
        }
        //生成token，并保存在数据库
        R result = userTokenService.createToken(user.getId());

        //给用户返回token
        return result;
    }
}
